package org.example.everyday;

import java.util.ArrayList;
import java.util.List;

/**
 * https://leetcode-cn.com/problems/find-the-closest-palindrome/
 */
public class Lc564 {

    public static void main(String[] args) {
        Lc564 lc564 = new Lc564();
        String s = "1234";
        String result = lc564.nearestPalindromic(s);
        System.out.println(result);
    }


    public String nearestPalindromic(String n) {
        long selfNumber = Long.parseLong(n), ans = -1;
        List<Long> cadidates = getCandidates(n);
        for (long cadidate : cadidates){
            if(cadidate != selfNumber){
                if(ans == -1
                        || Math.abs(cadidate - selfNumber) < Math.abs(ans - selfNumber)
                        || Math.abs(cadidate - selfNumber) == Math.abs(ans - selfNumber) && cadidate < ans){
                    ans = cadidate;
                }
            }
        }
        return Long.toString(ans);
    }

    private List<Long> getCandidates(String n) {
        int len = n.length();
        List<Long> cadidates = new ArrayList<Long>(){{
            add((long)Math.pow(10,len - 1) - 1);
            add((long)Math.pow(10,len) + 1);
        }};
        long selfPrefix = Long.parseLong(n.substring(0,(len + 1) / 2));
        for(long i = selfPrefix - 1;i <= selfPrefix + 1; i++){
            StringBuilder sb = new StringBuilder();
            String prefix = String.valueOf(i);
            sb.append(prefix);

            StringBuilder suffix = new StringBuilder(prefix).reverse();
            sb.append(suffix.substring(len & 1));
            String cadidate = sb.toString();
            cadidates.add(Long.parseLong(cadidate));
        }
        return cadidates;
    }

}
